<template>
  <VfDataTable
    ref="tableRef"
    class='select-none'
    v-bind="tableOptions"
    @menuClick="({ menu }) => handleClick(menu.code)"
    @checkboxAll="tableCheckboxChange"
    @checkboxChange="tableCheckboxChange"
  >
    <template #toolbar_left>
      <div class="field-table-toolbar-left">
        <!-- 新增行 -->
        <el-button plain size="small" type="primary" @click="handleClick('add')">新增行</el-button>
        <!-- 合并行 -->
        <el-button plain size="small" type="primary" :disabled="!tableChecked" @click="handleClick('merge')">合并行</el-button>
        <!-- 拆分行 -->
        <el-popconfirm
          class="vf-popconfirm"
          width="190"
          title="确定拆分选中的数据？"
          cancel-button-type="default"
          cancel-button-text="取消"
          confirm-button-text="确定"
          confirm-button-type="primary"
          :teleported="false"
          @confirm="handleClick('split')"
        >
          <template #reference>
            <el-button plain size="small" type="primary" :disabled="splitBtnDisabled">拆分行</el-button>
          </template>
        </el-popconfirm>
        <!-- 删除行 -->
        <el-popconfirm
          width="190"
          title="确定删除选中的数据？"
          cancel-button-type="default"
          cancel-button-text="取消"
          confirm-button-text="确定"
          confirm-button-type="danger"
          :teleported="false"
          @confirm="handleClick('delete')"
        >
          <template #reference>
            <el-button plain size="small" type="danger" :disabled="!tableCheckedItems.length"
              >删除行</el-button
            >
          </template>
        </el-popconfirm>
        <!-- 清空行 -->
        <el-popconfirm
          width="190"
          title="确定清空表格数据？"
          cancel-button-type="default"
          cancel-button-text="取消"
          confirm-button-text="确定"
          confirm-button-type="danger"
          :teleported="false"
          @confirm="tableOptions.data = []"
        >
          <template #reference>
            <el-button plain size="small" type="danger">清空行</el-button>
          </template>
        </el-popconfirm>
      </div>
    </template>
    <template #toolbar_right>
      <el-popconfirm
        width="190"
        title="导入的数据将覆盖已存在的数据？"
        cancel-button-type="default"
        cancel-button-text="取消"
        confirm-button-text="继续"
        confirm-button-type="primary"
        :teleported="false"
        @confirm="importColsDialogOpen"
      >
        <template #reference>
          <el-button plain size="small" type="primary">导入</el-button>
        </template>
      </el-popconfirm>
    </template>
    <template #drag_lot>
      <VfIcon name="iv-icon-move" />
    </template>
    <!-- 超链接配置 -->
    <template #edit_input_link="{row, column}">
      <span v-if="TableUtils.isExistChildren(row)">{{ row[column.field] }}</span>
      <el-input v-else size='default' v-model="row[column.field]" :readonly="true" placeholder='请设置' >
        <template #suffix>
          <el-icon @click="linkInfoDialogOpen({row, column})" class="el-input__icon"><Tools /></el-icon>
        </template>
      </el-input>
    </template>
    <!-- 渲染函数 -->
    <template #edit_render_func="{row, column}">
      <el-button
        size="small" round :icon="Edit"
        :type="row[column.field] ? 'primary' : 'default'"
        @click="codeEditorOpen(row, column)"
      />
    </template>
    <!-- 格式化函数 -->
    <template #edit_format_func="{row, column}">
      <el-button
        size="small" round :icon="Edit"
        :type="row[column.field] ? 'primary' : 'default'"
        :disabled="!!row.formatRule"
        @click="codeEditorOpen(row, column)"
      />
    </template>
  </VfDataTable>
  <CodeEditorDialog ref="codeDialogRef" :="codeDialogAttrs" @confirm="codeEditorConfirm"/>
  <!-- 超链接编辑面板 -->
  <HyperlinkCfgDialog ref="linkInfoDialogRef" :field-options="linkInfoFields" @confirm="linkInfoDialogConfirm"/>
  <!-- 导入字段数据面板 -->
  <ImportColumnsDialog ref="importColsDialogRef" @confirm="importColsDialogConfirm"/>
</template>

<script setup>
import TableUtils from '@/components/tables/cfg/table-utils'

import { VfDataTable } from '@/components/vf-table';
import { HyperlinkCfgDialog, ImportColumnsDialog, CodeEditorDialog } from '@/components/dialogs'

import { Tools, Edit } from '@element-plus/icons-vue'
import { ref, reactive, onMounted, watch, onBeforeMount } from 'vue';

import { useRowHandle } from './hook/useRowHandle'
import { useSortHandle } from './hook/useSortHandle'
import { useDataHandle } from '@/components/tables/hook/useDataHandle'
import { useTableColumns } from './cfg/table-columns'
import { DEFAULT_FIELD_ROW } from '@/components/tables/cfg/table-cons'

const props = defineProps({
  fieldOptions: { type: Array, default: [] },
});

// 表格ref对象
const tableRef = ref(null)
// 表格配置
const tableOptions = reactive({
  data: [],
  class: 'field-table',
  stripe: false,
  columns: [],
  loading: false,
  keyField: 'id',
  minHeight: 350,
  boxConfig: true,
  seqConfig: false,
  treeConfig: {
    indent: 15,
    reserve: true,
    showLine: false,
    rowField: 'id',
    expandAll: true,
    transform: false,
    parentField: 'parentId',
  },
  menuConfig: {
    className: 'designer-select-fixed',
    body: {
      disabled: false,
      options: [
        [
          { code: 'add', name: '新建行', prefixIcon: 'vxe-icon-square-plus', visible: true, disabled: false },
          { code: 'merge', name: '合并行', prefixIcon: 'vxe-icon-merge-cells', visible: true, disabled: false },
          { code: 'split', name: '拆分行', prefixIcon: 'vxe-icon-cut', visible: true, disabled: false },
        ],
      ],
    },
  },
  pagerConfig: false,
  rowClassName: ({ row }) => {
    if (row.children && row.children.length > 0) {
      return 'marge-row-item';
    } else {
      return '';
    }
  },
  showOverflow: 'ellipsis',
  toolbarConfig: { enabled: true, refresh: false },
  checkboxConfig: { checkStrictly: false },
});
/** 初始化表格字段 */
const initTableColumns = () => {
  const { fieldOptions } = props
  tableOptions.columns = useTableColumns().getColumns({ fieldOptions });
}
watch(
  () => props.fieldOptions,
  (newValue, oldValue) => {
    if (newValue && newValue.length) {
      initTableColumns();
    }
  },
  { deep: false, immediate: false },
);

const hooksParams = { props, tableRef, tableOptions, templateRow: DEFAULT_FIELD_ROW }
// 表格数据操作
const {
  tableNodeMap,
  setTableData,
  getTableData,
  parseTableData,
  filterTableData,
  validateFieldData,
  getPreviewTableData
} = useDataHandle(hooksParams)
// 表格行操作 新增 合并 拆分 删除.....
const {
  handleClick,
  tableChecked,
  splitBtnDisabled,
  tableCheckedItems,
  tableCheckboxChange
} = useRowHandle({ ...hooksParams, tableDataHandle: { parseTableData, filterTableData } })
// 表格排序操作
const {
  initSortable
} = useSortHandle({ ...hooksParams, tableDataHandle: { tableNodeMap } })

const validateTableData = () => {
  const validInfo = validateFieldData()
  if (validInfo.valid) {
    return true
  } else {
    TableUtils.openMessage(`字段明细：${validInfo.msg}`)
    return false
  }
}

// 超链接弹窗录入
const tableEditInfo = reactive({
  row: null,
  column: null
})
const linkInfoFields = ref([])
const linkInfoDialogRef = ref(null)
const linkInfoDialogOpen = ({ row, column }) => {
  tableEditInfo.row = row
  tableEditInfo.column = column
  linkInfoFields.value = getTableData(false).map(item => {
    return {
      label: item.title,
      value: item.field
    }
  })
  linkInfoDialogRef.value.handleOpen({ row, column })
}
const linkInfoDialogConfirm = (content) => {
  const { row, column } = tableEditInfo
  row[column.field] = content
}

const importColsDialogRef = ref(null)
const importColsDialogOpen = () => {
  importColsDialogRef.value.handleOpen()
}
const importColsDialogConfirm = (content) => {
  setTableData(content)
}

const codeDialogRef = ref()
const codeDialogAttrs = reactive({
  title: '代码编辑',
  frontAlert: ''
})
const codeEditorOpen = (row, column) => {
  tableEditInfo.row = row
  tableEditInfo.column = column

  codeDialogAttrs.title = `字段【${row.field}】${column.title}编辑`
  let funcParamTips = `params`
  if (column.field === 'renderFunc') funcParamTips = `h, params, components`
  codeDialogAttrs.frontAlert = `column.${column.field} (${funcParamTips}) {`
  codeDialogRef.value.handleOpen(row[column.field])
}
const codeEditorConfirm = (content) => {
  const { row, column } = tableEditInfo
  row[column.field] = content
}

// 执行字段初始化
initTableColumns()

// onMounted
onBeforeMount(() => {
  tableOptions.loading = true
})
onMounted(() => {
  initSortable();
})

defineExpose({
  setTableData,
  getTableData,
  validateTableData,
  getPreviewTableData
})

</script>

<style lang="scss" scoped>
.select-none {
  user-select: none;
  -moz-user-select: none;
  -webkit-user-select: none;
  -ms-user-select: none; 
}
:deep(.not-edit) {
  background: #f4f4f4;
  cursor: not-allowed;
}
:deep(.cell-full) {
  > .vxe-cell {
    height: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }
}
:deep(.el-input-number) {
  width: 100%;
  .el-input__wrapper {
    padding-left: 0;
    padding-right: 0;
  }
  .el-input-number__decrease,
  .el-input-number__increase {
    display: none !important;
  }
}
:deep(.vxe-cell) {
  .vxe-input>.vxe-input--inner {
    padding-left: 6px;
  }
}
.el-input__icon {
  cursor: pointer;
  &:hover {
    color: var(--el-color-primary);
  }
}
.field-table-toolbar-left {
  :deep(.el-button) {
    margin-left: 12px;
  }
}
</style>
<style lang="scss">
</style>